package com.example.reschain;

import java.util.concurrent.Exchanger;

public class ExchangerExample {

    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();

        // 创建两个线程，分别代表生产者和消费者
        Thread producer = new Thread(new Producer(exchanger));
        Thread consumer = new Thread(new Consumer(exchanger));

        producer.start();
        consumer.start();
    }

    static class Producer implements Runnable {

        private Exchanger<String> exchanger;

        public Producer(Exchanger<String> exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            try {
                String data = "Produced Data";
                System.out.println("Producer is producing: " + data);

                // 交换数据
                String receivedData = exchanger.exchange(data);
                System.out.println("Producer received: " + receivedData);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Consumer implements Runnable {
        private Exchanger<String> exchanger;

        public Consumer(Exchanger<String> exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            try {
                String data = "Consumed Data";
                System.out.println("Consumer is consuming: " + data);

                // 交换数据
                String receivedData = exchanger.exchange(data);
                System.out.println("Consumer received: " + receivedData);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}